﻿$(document).ready(function() {

	$.namespace("category", {
		inherited: true,

		InitialiseControl: function() {
			$.fn.category.LoadCategoryGrid();
		},

		LoadCategoryGrid: function() {

			var tabContent = $("#CategoriesContainer").children(".TabContent");

			var proxy = new Ext.data.HttpProxy({
				url: 'Data/Categories.aspx'
			});

			var reader = new Ext.data.JsonReader({
				root: 'Data',
				totalProperty: 'Count',
				idProperty: 'CategoryId',
				fields: [
					{ name: 'CategoryId', type: 'int' },
					{ name: 'CategoryName', type: 'string', allowBlank: false },
					{ name: 'BudgetAmount', type: 'float', allowBlank: false },
					{ name: 'IsActive', type: 'boolean' },
					{ name: 'Timestamp', type: 'date', dateFormat: 'M$' },
					{ name: 'Version', type: 'auto' }
				]
			});

			var writer = new Ext.data.JsonWriter({
				encode: true,   // <-- don't return encoded JSON -- causes Ext.Ajax#request to send data using 
								// jsonData config rather than HTTP params
				writeAllFields: true
			});

			var store = new Ext.data.Store({
				id: 'dsCategores',
				proxy: proxy,
				reader: reader,
				writer: writer,
				listeners: {
					'update': function(store, record, operation) {
						store.commitChanges();
					},
					'remove': function(store, record, index) {
						store.commitChanges();
					}
				}
			});

			var colModel = new Ext.grid.ColumnModel({
				defaults: {
					sortable: true
				},
				columns: [
					{header: 'Name', dataIndex: 'CategoryName', editor: new Ext.form.TextField({}) },
					{ header: 'Budget Amount', dataIndex: 'BudgetAmount', xtype: 'numbercolumn', format: '$0,0.00', align: 'right', editor: new Ext.form.NumberField({}) },
					{ header: 'Active', dataIndex: 'IsActive', xtype: 'booleancolumn', trueText: 'Yes', falseText: 'No', align: 'center', editor: new Ext.form.Checkbox({}) }
				]
			});

			// use RowEditor for editing
			var editor = new Ext.ux.grid.RowEditor({
				saveText: 'Update'
			});

			var grid = new Ext.grid.GridPanel({
				iconCls: 'icon-grid',
				frame: true,
				title: 'Categories',
				loadMask: true,
				autoScroll: true,
				height: 300,
				store: store,
				plugins: [editor],
				colModel: colModel,
				tbar: [{
					text: 'Add',
					iconCls: 'silk-add',
					handler: function(btn, ev) {
						var u = new grid.store.recordType({
							Description: '',
							Amount: '',
							IsActive: true
						});
						editor.stopEditing();
						grid.store.insert(0, u);
						editor.startEditing(0);
					}
				}, '-', '->', '-', {
					text: 'refresh',
					iconCls: 'silk-table-refresh',
					handler: function() {
						grid.store.load();
					}
				}],
				viewConfig: {
					forceFit: true
				}
			});

			grid.render(tabContent[0]);

			store.load();
		}
	});
});